<?php

class Application_Model_Mapper_GroupmemberMapper
{
	protected $_dbTable;

	public function setDbTable ($dbTable)
	{
		
		if (is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
		
	}

	public function getDbTable ()
	{
		
		if (null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Groupmember');
		}
		return $this->_dbTable;
		
	}

	public function add (Application_Model_Groupmember $groupmember)
	{			
		$generatedid = Helper_Idgenerator::getid();
		$generatedidcheck = $this->fetchGroupid($generatedid);
		if(empty($generatedidcheck)){
			$data = array(
				'id' => $generatedid,
				'userid' => $groupmember->getuserid(),
				'groupid' => $groupmember->getgroupid());
			return $this->getDbTable()->insert($data);
		}
		else{
			$this->add($groupmember);
		}
		
	}

	public function delete ($groupid, $id)
	{
		$this->getDbTable()->delete(array(
				'userid = ?' => $id,
				'groupid = ?' => $groupid
		));
	}

	public function deletegroup($groupid)
	{
		$table = $this->getDbTable();
		$where = $table->getAdapter()->quoteInto('groupid = ?', $groupid);
		$table->delete($where);
	}
	
	public function checkID ($id, $groupid)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('groupmember');
		$entry->where('groupmember.userid = ?', $id);
		$entry->where('groupmember.groupid = ?', $groupid);
		$entry1 = $entry->query()->fetch();
		if($entry1['userid'] == $id){
			return true;
		}
		else{
			return false;
		}
	}

	public function fetchGroupid($groupid)
	{
 		$db = Zend_Db_Table::getDefaultAdapter();
 		$entry = new Zend_Db_Select($db);
// 		$entry = $this->getDbTable();
		$entry->from('groupmember');
		$entry->where('groupmember.groupid = ?', $groupid);
		return $entry->query()->fetchall();
	}

}